<?php
namespace app\cgi\controller;

use think\Db;

class CaseGodown extends Base{
    private $stateTxt = ['1'=>'待分配','2'=>'已分配','3'=>'已归档'];
    private $endStateTxt = ['0'=>'','1'=>'调解成功','2'=>'调解失败'];
    protected function _initialize() {
        $this->mustLogin();
    }

    public function index(){
        $rs = Db::name('case_godown')->alias('a')
            ->join([
                ['__CASE_NATURE__ b','b.id=a.cn_id','LEFT'],
                ['__CASE_CATE__ c','c.id=a.cate_id','left'],
            ])
            ->where(['a.ty_id'=>$this->ty_id,'a.isdelete'=>0,'a.status'=>1,'a.state'=>$this->request->post('idx/d',0)+1])
            ->field('a.id,a.state,a.region,a.sn,a.from_user,a.from_time,a.from_mobile,a.people_num,a.money,a.input_name,a.do_name,a.end_state,a.end_state_txt,a.end_time,b.nature,c.cate,a.imgs')->page($this->request->post('page/d',1),20)->order('a.end_time desc,a.from_time desc,a.id desc')->select()?:[];
        foreach ( $rs as $k=>&$v ) {
            $v['imgs'] = '' == $v['imgs'] ? [] : explode(',',$v['imgs']);
            $v['from_time'] = date('Y-m-d',$v['from_time']);
            $v['state_txt'] = isset($this->stateTxt[$v['state']]) ? $this->stateTxt[$v['state']] : '';
            '' == $v['end_state_txt'] && $v['end_state_txt'] = isset($this->endStateTxt[$v['end_state']]) ? $this->endStateTxt[$v['end_state']] : '';
        }
        $return = ['lists'=>$rs,'isEnd'=>count($rs)<20?true : false];
        if( $this->request->post('chk_btn') ) {
            $return['btns'] = [
                'edit'=>\Rbac::AccessCheckCgi($this->communityUser['id'],'edit','CaseGodown'),
                'details'=>\Rbac::AccessCheckCgi($this->communityUser['id'],'details','CaseGodown'),
                'allot'=>\Rbac::AccessCheckCgi($this->communityUser['id'],'details','CaseGodown'),
            ];
        }
        $this->response('',$return);
    }
    /*可分配任务人， 分配任务*/
    public function allot(){
        $id = $this->request->post('id/d');
        $case = Db::name('case_godown')->alias('a')->join('__CASE_NATURE__ b','b.id=a.cn_id','LEFT')->where(['a.ty_id'=>$this->ty_id,'a.id'=>$id,'a.status'=>1,'a.isdelete'=>0])->field('a.state,a.people_num,a.money,a.cn_id,a.do_time,a.process,a.update_time,b.number,b.json_str')->find();
        !$case && $this->responseError('案件不存在或已被删除');
        switch ( $case['state'] ) {
            case 2:
                $this->responseError('案件已分配');
                break;
            case 3:
                $this->responseError('案件已归档');
                break;
        }
        if( $this->request->param('act') ) {
            $role_id = $this->request->post('role_id/d',0);
            ( (int)$case['update_time'] !== $this->request->post('t/d',0) ) && $this->responseError('该案件已经被其它人操作，请刷新页面');
            $user = Db::name('community_user')->alias('a')->join([
                ['__COMMUNITY_ROLE_USER__ b','b.user_id=a.id'],
                ['__COMMUNITY_ROLE__ d','d.id=b.role_id']
                ])
                ->field('a.id,a.realname,a.mobile,a.openid,d.name as role_name')->where(['a.ty_id'=>$this->ty_id,'b.role_id'=>$role_id,'a.id'=>$this->request->post('user_id/d',0),'a.status'=>1,'a.isdelete'=>0])->find();
            is_null($user) && $this->responseError('用户不存在或没有权限');
            $dbData = [
                'do_name'=>$user['realname'],
                'process'=>$this->request->post('process/d',0),
                'do_time'=>$this->request->post('do_time/d',0),
                'state'=>2,
                'update_time'=>time()
            ];
            Db::startTrans();
            try {
                $dbData['allot_id'] = Db::name('case_allot')->insertGetId([
                    'ty_id'=>$this->ty_id,
                    'case_id'=>$id,
                    'role_id'=>$role_id,
                    'role_name'=>$user['role_name'],
                    'from_id'=>$this->communityUser['id'],
                    'from_name'=>$this->communityUser['realname'],
                    'to_id'=>$user['id'],
                    'to_name'=>$user['realname'],
                    'status'=>1,
                    'create_time'=>time(),
                    'is_last'=>1===$this->request->post('is_last/d',0)?1:0,
                    'step'=>$dbData['process'],
                    'result_info'=>'',
                    'imgs'=>''
                ]);
                if( !Db::name('case_godown')->where(['id'=>$id,'state'=>1])->update($dbData) ) {
                    throw new \Exception('网络繁忙');
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->responseError($e->getMessage());
            }
            $form_id = $this->request->post('form_id','');
            if( $form_id && 'the formId is a mock one' !== $form_id  ) {
                Db::name('form_id')->insert(['ty_id'=>$this->ty_id,'user_id'=>$this->userInfo['id'],'from_id'=>$form_id,'create_time'=>time()]);
            }

            vendor('Message.Send');
            $send = new \Send();
            if( !$send::task_to($user['mobile'],'') ) {
                Db::name('msg_err')->insert([
                    'mobile'=>$user['mobile'],
                    'info'=>$send->getResp(),
                    'create_time'=>time()
                ]);
            }

            $this->response('分配成功');
            //分配
        } else {
            //查询可分配的角色
            $json_arr = json_decode($case['json_str'],true); //流程数组
            !$json_arr && $this->responseError('案件流程配置异常');
            $case['do_time'] = (int)$case['do_time'];$case['process'] = (int)$case['process'];
            $processCount = count($json_arr,0);
            if( !isset($json_arr[$case['process']]) ) {
                //没有当前流程 进入最后一次流程
                $case['process'] = $processCount-1;
                $case['do_time'] = 0;
            }
            $json_now = $json_arr[$case['process']]; //当前所在流程
            $key = $case['people_num'] > $case['number'] ? 2 : 1; //流程方式

            if( $case['do_time'] >= (int)$json_now['num'.$key] ) {
                //流程次数完成，下一个流程
                $case['do_time'] = 0;
                $case['process'] += 1;
                !isset($json_arr[$case['process']]) && $this->responseError('流程已结束');
                $json_now = $json_arr[$case['process']];
            }
            $role_id = $json_now['role'.$key];

            0 === (int)$role_id && $role_id = $json_now['role1'];

            $case['do_time'] += 1; //次数加1
            $lists = Db::name('community_user')->alias('a')->join([
                ['__COMMUNITY_ROLE_USER__ b','b.user_id=a.id'],
                ['__USER__ c','c.openid=a.openid','left'],
                ['__COMMUNITY_ROLE__ d','d.id=b.role_id']
            ])->field('a.id,a.realname,a.mobile,c.nickname,c.headimgurl,c.area,d.name as role_name')->where(['a.ty_id'=>$this->ty_id,'b.role_id'=>$role_id,'a.status'=>1,'a.isdelete'=>0])->order('a.last_login_time desc,a.id')->page($this->request->post('page/d',1),50)->select();

            $this->response('',
                [
                    'lists'=>$lists,
                    'post'=>['process'=>$case['process'],'do_time'=>$case['do_time'],'t'=>$case['update_time'],'role_id'=>$role_id,'is_last'=>$processCount-1===$case['process']?1:0],
                    'isEnd'=>count($lists)<50?true : false
                ]
            );

        }
    }
    /*详情*/
    public function details(){
        $id = $this->request->param('id/d',0);
        $return = Db::name('case_godown')->alias('a')
            ->join([
                ['__CASE_NATURE__ b','b.id=a.cn_id'],
                ['__CASE_CATE__ c','c.id=a.cate_id']
            ])
            ->field('a.region,a.sn,FROM_UNIXTIME(a.from_time,\'%Y-%m-%d\') as from_time,a.people_num,a.money,a.imgs,a.remark,b.nature,c.cate,a.do_time,a.process')->where(['a.id'=>$id,'a.isdelete'=>0,'a.status'=>1,'a.ty_id'=>$this->ty_id])->find();
        !$return && $this->responseError('案件不存在或已被删除');

        $return['imgs'] = $return['imgs'] ? explode(',',$return['imgs']) : [];
        $return['visitors_arr'] = Db::name('case_visitors')->field("visitor,mobile,if(sex=1,'男','女') as sex,idcard,address")->where(['case_id'=>$id])->order('id')->select()?:[];
        $return['company_arr'] = Db::name('case_company')->field("company,address,lxr,mobile,if(sex=1,'男','女') as sex")->where(['case_id'=>$id])->order('id')->select()?:[];
        $return['allot_log'] = Db::name('case_allot')->alias('a')->join('__COMMUNITY_USER__ b','b.id=a.to_id')
            ->field('a.from_name,a.to_id,a.to_name,a.role_id,a.role_name,a.status,a.status_txt,FROM_UNIXTIME(a.result_time,\'%Y-%m-%d %H:%i\') as result_time,a.result_info,a.imgs,b.mobile')->where(['a.case_id'=>$id,'a.isdelete'=>0])->order('a.id')->select()?:[];
        $return['do_user_id'] = 0;
        foreach ( $return['allot_log'] as &$v){
            $v['imgs'] = '' === $v['imgs'] ? []:explode(',',$v['imgs']);
            1 === (int)$v['status'] && $return['do_user_id'] = $v['to_id'];
        }
        if( $return['do_user_id'] == $this->communityUser['id'] ) {
            $arbitration = \Rbac::AccessCheckCgi($this->communityUser['id'],'arbitration','CaseGodown');
            if( $arbitration ) {
                $return['btns'] = [
                    ['type'=>'submit','txt'=>'已调解','id'=>'requet_ok','cls'=>''],
                    ['type'=>'submit','txt'=>'引导仲裁','id'=>'arbitration','cls'=>'btn2'],
                    ['type'=>'submit','txt'=>'申请监察执法介入','id'=>'requet_no','cls'=>'btn2']
                ];
            } else {
                $return['btns'] = [
                    ['type'=>'submit','txt'=>'已调解','id'=>'requet_ok','cls'=>''],
                    ['type'=>'submit','txt'=>'调解不成','id'=>'requet_no','cls'=>'btn2']
                ];
            }
        } else {
            $return['btns'] = [];
        }
        $this->response('',$return);

    }
    /*任务列表*/
    public function task(){
        $rs = Db::name('case_godown')->alias('a')
            ->join([
                ['__CASE_NATURE__ b','b.id=a.cn_id','LEFT'],
                ['__CASE_CATE__ c','c.id=a.cate_id','left'],
                ['__CASE_ALLOT__ d','d.id=a.allot_id','left']
            ])
            ->where(['a.ty_id'=>$this->ty_id,'a.isdelete'=>0,'a.status'=>1,'a.state'=>2,'d.to_id'=>$this->communityUser['id']])
            ->field('a.id,a.state,a.region,a.sn,a.from_user,a.from_time,a.from_mobile,a.people_num,a.money,a.input_name,a.do_name,a.end_state,a.end_time,b.nature,c.cate,a.imgs')->page($this->request->post('page/d',1),20)
            ->order('a.end_time desc,a.from_time desc,a.id desc')->select()?:[];
        foreach ( $rs as $k=>&$v ) {
            $v['imgs'] = '' == $v['imgs'] ? [] : explode(',',$v['imgs']);
            $v['from_time'] = date('Y-m-d',$v['from_time']);
            $v['state_txt'] = isset($this->stateTxt[$v['state']]) ? $this->stateTxt[$v['state']] : '';
            $v['end_state_txt'] = isset($this->endStateTxt[$v['end_state']]) ? $this->endStateTxt[$v['end_state']] : '';
        }
        $this->response('',['lists'=>$rs,'isEnd'=>count($rs)<20?true : false]);
    }
    /*处理结果*/
    public function result(){
        $id = $this->request->post('id/d',0);
        $case = Db::name('case_godown')->alias('a')->join([
                ['__CASE_ALLOT__ b','b.id=a.allot_id'],
                ['__COMMUNITY_USER__ c','c.id=b.from_id'],
            ])
            ->field('a.state,a.allot_id,b.to_id,b.to_name,b.status,b.is_last,c.openid,c.mobile')->where(['a.id'=>$id,'a.isdelete'=>0,'a.status'=>1,'a.ty_id'=>$this->ty_id])->find();
        !$case && $this->responseError('案件不存在或已被删除');
        (int)$case['to_id'] !== (int)$this->communityUser['id'] && $this->responseError('只有['.$case['to_name'].'才可以处理]');
        3 === (int)$case['state'] && $this->responseError('案件已归档，不允许操作');
        1 !== (int)$case['status'] && $this->responseError('案件处理，不允许操作');
        $time = time();
        $dbData = [
            'result_info'=>$this->request->post('result_info','',''),
            'imgs'=>implode(',',$this->request->post('up_imgs/a',[])),
            'status'=>2 === $this->request->post('status/d')?2:3,
            'result_time'=>$time,
            'update_time'=>$time
        ];

        $godownData = ['allot_id'=>0,'do_name'=>'','state'=>( 1 === (int)$case['is_last'] || 2==$dbData['status'] )?3:1,'update_time'=>$time];
        if( 3 === $godownData['state'] ) {
            $godownData['end_time'] = $time;
            if( 2==$dbData['status'] ) {
                $godownData['end_state'] = 1;
                $godownData['end_state_txt'] = '调解成功';
            } else {
                $godownData['end_state'] = 2;
                $godownData['end_state_txt'] = '调解失败';
            }
        }
        Db::startTrans();
        try {
            if( !Db::name('case_godown')->where(['id'=>$id,'state'=>2,'allot_id'=>$case['allot_id']])->update($godownData) ) {
                throw new \Exception('网络繁忙');
            }
            Db::name('case_allot')->where(['id'=>$case['allot_id']])->update($dbData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->responseError($e->getMessage());
        }
        $form_id = $this->request->post('form_id','');
        if( $form_id && 'the formId is a mock one' !== $form_id  ) {
            Db::name('form_id')->insert(['ty_id'=>$this->ty_id,'user_id'=>$this->userInfo['id'],'from_id'=>$form_id,'create_time'=>$time]);
        }
        if( 3 != $godownData['state'] ) {
            vendor('Message.Send');
            $send = new \Send();
            if (!$send::task_result($case['mobile'], '')) {
                Db::name('msg_err')->insert([
                    'mobile' => $case['mobile'],
                    'info' => $send->getResp(),
                    'create_time' => time()
                ]);
            }
        }
        $this->response('保存成功');
    }

    /*引导仲裁*/
    public function arbitration(){
        $id = $this->request->post('id/d',0);
        $case = Db::name('case_godown')->alias('a')->join([
            ['__CASE_ALLOT__ b','b.id=a.allot_id'],
            ['__COMMUNITY_USER__ c','c.id=b.from_id'],
        ])
            ->field('a.state,a.allot_id,b.to_id,b.to_name,b.status,b.is_last,c.openid,c.mobile')->where(['a.id'=>$id,'a.isdelete'=>0,'a.status'=>1,'a.ty_id'=>$this->ty_id])->find();
        !$case && $this->responseError('案件不存在或已被删除');
        (int)$case['to_id'] !== (int)$this->communityUser['id'] && $this->responseError('只有['.$case['to_name'].'才可以处理]');
        3 === (int)$case['state'] && $this->responseError('案件已归档，不允许操作');
        1 !== (int)$case['status'] && $this->responseError('案件处理，不允许操作');
        $time = time();
        $dbData = [
            'result_info'=>$this->request->post('result_info','',''),
            'imgs'=>implode(',',$this->request->post('up_imgs/a',[])),
            'status'=>2,
            'status_txt'=>'引导仲裁',
            'result_time'=>$time,
            'update_time'=>$time
        ];

        $godownData = ['allot_id'=>0,'do_name'=>'','state'=>3,'update_time'=>$time,'end_time'=>$time,'end_state'=>2,'end_state_txt'=>'申请仲裁'];

        Db::startTrans();
        try {
            if( !Db::name('case_godown')->where(['id'=>$id,'state'=>2,'allot_id'=>$case['allot_id']])->update($godownData) ) {
                throw new \Exception('网络繁忙');
            }
            Db::name('case_allot')->where(['id'=>$case['allot_id']])->update($dbData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->responseError($e->getMessage());
        }
        $form_id = $this->request->post('form_id','');
        if( $form_id && 'the formId is a mock one' !== $form_id  ) {
            Db::name('form_id')->insert(['ty_id'=>$this->ty_id,'user_id'=>$this->userInfo['id'],'from_id'=>$form_id,'create_time'=>$time]);
        }
//        vendor('Message.Send');
//        $send = new \Send();
//        if( !$send::task_result($case['mobile'],'') ) {
//            Db::name('msg_err')->insert([
//                'mobile'=>$case['mobile'],
//                'info'=>$send->getResp(),
//                'create_time'=>time()
//            ]);
//        }
        $this->response('保存成功');
    }

    public function add(){
        if( $this->request->param('act') ) {
            $godown = $this->request->post('godown/a',[]);
            $imgs = $this->request->post('imgs/a',[]);
            $visitors = $this->request->post('visitors/a');
            $company = $this->request->post('company/a');
            $time = time();
            $godown['imgs'] = implode(',',$imgs);
            $godown['from_user'] = $visitors[0]['visitor'];
            $godown['from_mobile'] = $visitors[0]['mobile'];
            $godown['people_num'] = (int)$godown['people_num'];
            $godown['money'] = (float)$godown['money'];
            $godown['from_time'] = strtotime($godown['from_time']);
            $godown['status'] = 1;
            $godown['state'] = 1;
            $godown['ty_id'] = $this->ty_id;
            $godown['create_time'] = $time;
            $godown['input_id'] = $this->communityUser['id'];
            $godown['input_name'] = $this->communityUser['realname'];
            $form_id = $this->request->post('form_id');
            Db::startTrans();
            try {
                $godown['sn'] = $this->getCaseSn($godown['region']);
                $id = Db::name('case_godown')->insertGetId($godown);
                foreach ($visitors as $k=>&$v){
                    $v['id'] = $k;
                    $v['ty_id'] = $godown['ty_id'];
                    $v['case_id'] = $id;
                    $v['update_time'] = $time;
                }
                foreach ($company as $k=>&$v){
                    $v['id'] = $k;
                    $v['ty_id'] = $godown['ty_id'];
                    $v['case_id'] = $id;
                    $v['update_time'] = $time;
                }
                Db::name('case_visitors')->insertAll($visitors);
                Db::name('case_company')->insertAll($company);
                if( $form_id && 'the formId is a mock one' !== $form_id  ) {
                    Db::name('form_id')->insert(['ty_id'=>$godown['ty_id'],'user_id'=>$this->userInfo['id'],'from_id'=>$form_id,'create_time'=>$time]);
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->responseError($e->getMessage());
            }

            $this->response('添加成功',$id);
        } else {
            $this->response('',[
                'nature_arr'=>Db::name('case_nature')->where(['ty_id'=>$this->ty_id,'isdelete'=>0])->field('id,nature')->order('sort desc,id')->select()?:[],
                'cate_arr'=>Db::name('case_cate')->where(['ty_id'=>$this->ty_id,'isdelete'=>0])->field('id,cate')->order('sort desc,id')->select()?:[],
                'region_arr'=>Db::name('region')->where(['ty_id'=>$this->ty_id,'isdelete'=>0])->field('code_en,code_cn')->order('sort desc,id')->select()?:[],
                'from_time'=>date('Y-m-d'),
            ]);
        }
    }

    public function edit(){
        $id = $this->request->param('id/d',0);
        $return = Db::name('case_godown')->field('id,cn_id,cate_id,region,FROM_UNIXTIME(from_time,\'%Y-%m-%d\') as from_time,people_num,money,imgs,remark')->where(['id'=>$id,'isdelete'=>0,'status'=>1,'ty_id'=>$this->ty_id])->find();
        !$return && $this->responseError('案件不存在或已被删除');
        if( $this->request->param('act') ) {
            $godown = $this->request->post('godown/a',[]);
            $imgs = $this->request->post('imgs/a',[]);
            $visitors = $this->request->post('visitors/a');
            $company = $this->request->post('company/a');
            if( isset($godown['cn_id']) ) {
                unset($godown['cn_id']);
            }
            if( isset($godown['region']) ) {
                unset($godown['region']);
            }
            $time = time();
            $godown['imgs'] = implode(',',$imgs);
            $godown['from_user'] = $visitors[0]['visitor'];
            $godown['from_mobile'] = $visitors[0]['mobile'];
            $godown['people_num'] = (int)$godown['people_num'];
            $godown['money'] = (float)$godown['money'];
            $godown['from_time'] = strtotime($godown['from_time']);
            $godown['ty_id'] = $this->ty_id;
            $godown['create_time'] = $time;
            $godown['input_id'] = $this->communityUser['id'];
            $godown['input_name'] = $this->communityUser['realname'];
            $form_id = $this->request->post('form_id');
            Db::startTrans();
            try {
                Db::name('case_godown')->where(['id'=>$id])->update($godown);
                Db::name('case_visitors')->where(['case_id'=>$id])->delete();
                Db::name('case_company')->where(['case_id'=>$id])->delete();
                foreach ($visitors as $k=>&$v){
                    $v['id'] = $k;
                    $v['ty_id'] = $godown['ty_id'];
                    $v['case_id'] = $id;
                    $v['update_time'] = $time;
                }
                foreach ($company as $k=>&$v){
                    $v['id'] = $k;
                    $v['ty_id'] = $godown['ty_id'];
                    $v['case_id'] = $id;
                    $v['update_time'] = $time;
                }
                Db::name('case_visitors')->insertAll($visitors);
                Db::name('case_company')->insertAll($company);
                if( $form_id && 'the formId is a mock one' !== $form_id  ) {
                    Db::name('form_id')->insert(['ty_id'=>$godown['ty_id'],'user_id'=>$this->userInfo['id'],'from_id'=>$form_id,'create_time'=>$time]);
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->responseError($e->getMessage());
            }
            $this->response('修改成功');
        } else {

            if( $return['imgs'] ) {
                $imgs = explode(',',$return['imgs']);
                $return['imgs'] = [];
                foreach ( $imgs as $v){
                    $return['imgs'][] = [
                        'src'=>$v,
                    ];
                }
            } else {
                $return['imgs'] = [];
            }

            $return['nature_arr'] = Db::name('case_nature')->where(['ty_id'=>$this->ty_id,'isdelete'=>0])->field("id,nature,IF(({$return['cn_id']}=id),'1','') as checked")->order('sort desc,id')->select()?:[];

            $return['cate_arr'] = Db::name('case_cate')->where(['ty_id'=>$this->ty_id,'isdelete'=>0])->field("id,cate,IF(({$return['cate_id']}=id),'1','') as checked")->order('sort desc,id')->select()?:[];
            $return['region_arr'] = Db::name('region')->where(['ty_id'=>$this->ty_id,'isdelete'=>0])->field('code_en,code_cn')->order('sort desc,id')->select()?:[];
            $return['visitors_arr'] = Db::name('case_visitors')->field('visitor,mobile,sex,idcard,address')->where(['case_id'=>$id])->order('id')->select()?:[];
            $return['company_arr'] = Db::name('case_company')->field('company,address,lxr,mobile,sex')->where(['case_id'=>$id])->order('id')->select()?:[];
            foreach ($return['cate_arr'] as $k=>$v ) {
                if( $v['id'] == $return['cate_id'] ) {
                    $return['cate_index'] = $k;
                    break;
                }
            }
            foreach ( $return['visitors_arr'] as $v ) {
                $return['visitors'][] = 1;
            }
            foreach ( $return['company_arr'] as $v ) {
                $return['company'][] = 1;
            }
            $this->response('',$return);
        }
    }

    private function getCaseSn($region){
        $ymd = date('Ymd');
        $num = Db::name('case_sn')->where(['ty_id'=>$this->ty_id,'region'=>$region,'ymd'=>$ymd])->value('num');
        if( is_null($num) ) {
            $num = 0;
            Db::name('case_sn')->insert(['ty_id'=>$this->ty_id,'region'=>$region,'ymd'=>date('Ymd'),'num'=>1]);
        } else {
            Db::name('case_sn')->where(['ty_id'=>$this->ty_id,'region'=>$region,'ymd'=>date('Ymd'),'num'=>$num])->setInc('num',1);
        }
        $num += 1;
        return $region.$ymd.substr('000'.$num,-4,4);
    }
}
